package com.hymall.service.wx;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.hymall.bean.*;
import com.hymall.bean.bo.WxGoodsListBO;
import com.hymall.bean.common.BasePageInfo;
import com.hymall.bean.common.CommonData;
import com.hymall.bean.vo.*;
import com.hymall.mapper.*;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author: 章鹏
 * @description 小程序商品模块
 * @date: 2022/7/19 19:12
 */
@Service
public class WxGoodsServiceImpl implements WxGoodsService {
    @Autowired
    MarketGoodsMapper marketGoodsMapper;
    @Autowired
    MarketCollectMapper marketCollectMapper;
    @Autowired
    MarketCommentMapper marketCommentMapper;
    @Autowired
    AdminConfigMapper adminConfigMapper;
    @Autowired
    MarketBrandMapper marketBrandMapper;
    @Autowired
    MarketGoodsSpecificationMapper marketGoodsSpecificationMapper;
    @Autowired
    MarketIssueMapper marketIssueMapper;
    @Autowired
    MarketGoodsProductMapper marketGoodsProductMapper;
    @Autowired
    MarketGoodsAttributeMapper marketGoodsAttributeMapper;
    @Autowired
    MarketCategoryMapper marketCategoryMapper;
    @Autowired
    MarketUserMapper marketUserMapper;
    @Autowired
    MarketSearchHistoryMapper marketSearchHistoryMapper;

    /**
     * @param []
     * @return int
     * @author 章鹏
     * @description 获取上架商品数量
     * @date 2022/7/20 9:51
     */
    @Override
    public int getOnSaleNum() {
        MarketGoodsExample marketGoodsExample = new MarketGoodsExample();
        marketGoodsExample.createCriteria().andIsOnSaleEqualTo(true);
        long count = marketGoodsMapper.countByExample(marketGoodsExample);
        return (int) count;
    }

    /**
     * @param [goodsId]
     * @return com.hymall.bean.vo.WxGoodsDetailVO
     * @author 章鹏
     * @description 加载商品主页面
     * @date 2022/7/20 9:51
     */
    @Override
    public WxGoodsDetailVO getGoodsDetail(int goodsId) {
        WxGoodsDetailVO wxGoodsDetailVO = new WxGoodsDetailVO();

        // 获得userHasCollect 是否收藏
        // 通过subject获取userId 在通过goodsId和userId查找
        // 如果没有登录 默认是0
        byte userHasCollect = 0;
        Subject subject = SecurityUtils.getSubject();
        MarketUser marketUser = (MarketUser) subject.getPrincipal();
        if (marketUser != null) {
            Integer userId = marketUser.getId();
            MarketCollectExample collectExample = new MarketCollectExample();
            collectExample.createCriteria().andDeletedEqualTo(false).
                    andUserIdEqualTo(userId).andValueIdEqualTo(goodsId).andTypeEqualTo((byte) 0);
            List<MarketCollect> marketCollectList = marketCollectMapper.selectByExample(collectExample);
            userHasCollect = (byte) marketCollectList.size();
        }
        wxGoodsDetailVO.setUserHasCollect(userHasCollect);

        //shareImage 直接返回空

        //获得comment 评论
        WxGoodsDetailInnerCommentVO wxGoodsDetailInnerCommentVO = new WxGoodsDetailInnerCommentVO();
        MarketCommentExample commentExample = new MarketCommentExample();
        commentExample.createCriteria().andDeletedEqualTo(false)
                .andValueIdEqualTo(goodsId).andTypeEqualTo((byte) 0);
        List<MarketComment> data = marketCommentMapper.selectByExample(commentExample, "desc");
        //考虑是否只显示一部分评论
        List<MarketComment> dataLimted = data.stream().limit(5).collect(Collectors.toList());
        wxGoodsDetailInnerCommentVO.setCount(data.size());
        wxGoodsDetailInnerCommentVO.setData(dataLimted);
        wxGoodsDetailVO.setComment(wxGoodsDetailInnerCommentVO);

        //获得share 是否允许分享
        String value = adminConfigMapper.queryMarketMallConfigValue("market_wx_share");
        if ("true".equals(value)) {
            wxGoodsDetailVO.setShare(true);
        }

        //获得info 商品信息
        MarketGoods info = marketGoodsMapper.selectByPrimaryKey(goodsId);
        wxGoodsDetailVO.setInfo(info);

        //获得brand 品牌制造商
        Integer brandId = info.getBrandId();
        if (brandId != 0 && brandId != null) {
            MarketBrand marketBrand = marketBrandMapper.selectByPrimaryKey(brandId);
            wxGoodsDetailVO.setBrand(marketBrand);
        }

        //获得brand 规格规格表
        List<WXGoodsDetailInnerSpecificationVO> specificationList = new ArrayList<>();
        MarketGoodsSpecificationExample marketGoodsSpecificationExample = new MarketGoodsSpecificationExample();
        marketGoodsSpecificationExample.createCriteria().andGoodsIdEqualTo(goodsId);
        List<MarketGoodsSpecification> marketGoodsSpecificationList =
                marketGoodsSpecificationMapper.selectByExample(marketGoodsSpecificationExample);
        List<String> names = marketGoodsSpecificationList.stream().map(MarketGoodsSpecification::getSpecification).distinct().collect(Collectors.toList());
        for (String name : names) {
            WXGoodsDetailInnerSpecificationVO wxGoodsDetailInnerSpecificationVO = new WXGoodsDetailInnerSpecificationVO();
            wxGoodsDetailInnerSpecificationVO.setName(name);
            List<MarketGoodsSpecification> valueList = marketGoodsSpecificationList.stream().filter(s -> s.getSpecification().equals(name)).collect(Collectors.toList());
            wxGoodsDetailInnerSpecificationVO.setValueList(valueList);
            specificationList.add(wxGoodsDetailInnerSpecificationVO);
        }
        wxGoodsDetailVO.setSpecificationList(specificationList);

        //groupon 团购

        //获得issue 问答
        MarketIssueExample issueExample = new MarketIssueExample();
        issueExample.createCriteria().andDeletedEqualTo(false);
        List<MarketIssue> issue = marketIssueMapper.selectByExample(issueExample);
        wxGoodsDetailVO.setIssue(issue);

        //获得attribute 商品属性
        MarketGoodsAttributeExample marketGoodsAttributeExample = new MarketGoodsAttributeExample();
        marketGoodsAttributeExample.createCriteria().andGoodsIdEqualTo(goodsId);
        List<MarketGoodsAttribute> marketGoodsAttributeList = marketGoodsAttributeMapper.selectByExample(marketGoodsAttributeExample);
        wxGoodsDetailVO.setAttribute(marketGoodsAttributeList);

        //获得product 下单的商品页
        MarketGoodsProductExample marketGoodsProductExample = new MarketGoodsProductExample();
        marketGoodsProductExample.createCriteria().andGoodsIdEqualTo(goodsId);
        List<MarketGoodsProduct> productList = marketGoodsProductMapper.selectByExample(marketGoodsProductExample);
        wxGoodsDetailVO.setProductList(productList);

        return wxGoodsDetailVO;
    }

    /**
     * @param [categoryId]
     * @return com.hymall.bean.vo.WxGoodsCategoryVO
     * @author 章鹏
     * @description 获取一级类别 及其 所有的二级类别
     * @date 2022/7/20 9:51
     */
    @Override
    public WxGoodsCategoryVO getCategories(Integer categoryId) {
        // 这个id均为是二级id
        MarketCategory parentCategory;
        MarketCategory currentCategory;
        List<MarketCategory> brotherCategory;
        MarketCategory category = marketCategoryMapper.selectByPrimaryKey(categoryId);
        if (category.getPid() == 0) {
            // 类别id是一级id
            parentCategory = category;
            // 所有二级类别
            MarketCategoryExample categoryExample = new MarketCategoryExample();
            categoryExample.createCriteria().andDeletedEqualTo(false).andPidEqualTo(categoryId);
            brotherCategory = marketCategoryMapper.selectByExample(categoryExample);
            // 当前类别
            currentCategory = brotherCategory.get(0);
        } else {
            // 类别id是二级id
            currentCategory = category;
            // 一级类别
            parentCategory = marketCategoryMapper.selectByPrimaryKey(currentCategory.getPid());
            // 所有二级类别
            MarketCategoryExample categoryExample = new MarketCategoryExample();
            categoryExample.createCriteria().andDeletedEqualTo(false).andPidEqualTo(currentCategory.getPid());
            brotherCategory = marketCategoryMapper.selectByExample(categoryExample);
        }
        WxGoodsCategoryVO categoryVo = new WxGoodsCategoryVO();
        categoryVo.setBrotherCategory(brotherCategory);
        categoryVo.setCurrentCategory(currentCategory);
        categoryVo.setParentCategory(parentCategory);
        return categoryVo;
    }

    /**
     * @param [goodsId]
     * @return com.hymall.bean.common.CommonData
     * @author 章鹏
     * @description 商品详情 → 加载相关商品页面
     * @date 2022/7/20 10:23
     */
    @Override
    public CommonData getRelatedGoods(int goodsId) {
        MarketGoodsExample marketGoodsExample = new MarketGoodsExample();
        marketGoodsExample.createCriteria().andIdEqualTo(goodsId);
        List<MarketGoods> desc = marketGoodsMapper.selectByExample(marketGoodsExample, "desc");
        Integer categoryId = desc.get(0).getCategoryId();
        marketGoodsExample.clear();
        marketGoodsExample.createCriteria().andCategoryIdEqualTo(categoryId);
        List<MarketGoods> marketGoodsList1 = marketGoodsMapper.selectByExample(marketGoodsExample, "desc");
        //手动分页
        List<MarketGoods> marketGoodsList = marketGoodsList1.stream().limit(6).collect(Collectors.toList());
        List<WxGoodsRelatedVO> relatedGoodsList = new ArrayList<>();
        for (MarketGoods marketGoods : marketGoodsList) {
            WxGoodsRelatedVO wxGoodsRelatedVO = new WxGoodsRelatedVO();
            BeanUtils.copyProperties(marketGoods, wxGoodsRelatedVO);
            relatedGoodsList.add(wxGoodsRelatedVO);
        }
        int size = relatedGoodsList.size();
        //传入分页信息
        PageInfo<WxGoodsRelatedVO> pageInfo = new PageInfo<>();
        pageInfo.setList(relatedGoodsList);
        pageInfo.setPageNum(1);
        pageInfo.setPageSize(6);
        pageInfo.setTotal(size);
        pageInfo.setPages((size - 1) / pageInfo.getPageSize() + 1);
        return CommonData.data(pageInfo);
    }

    /**
     * @param [basePageInfo, wxGoodsListBO]
     * @return com.hymall.bean.vo.WxGoodsListVO
     * @author 章鹏
     * @description 商品列表
     * @date 2022/7/20 15:35
     */
    @Override
    public WxGoodsListVO list(BasePageInfo basePageInfo, WxGoodsListBO wxGoodsListBO) {
        WxGoodsListVO wxGoodsListVO = new WxGoodsListVO();
        //BeanUtils.copyProperties(basePageInfo,wxGoodsListVO);

        MarketGoodsExample marketGoodsExample = new MarketGoodsExample();
        //PageHelper分页
        PageHelper.startPage(basePageInfo.getPage(), basePageInfo.getLimit());
        //限定按照什么字段排序
        marketGoodsExample.setOrderByClause(basePageInfo.getSort());
        MarketGoodsExample.Criteria criteria = marketGoodsExample.createCriteria();
        if (wxGoodsListBO.getKeyword() != null) {
            criteria.andNameLike("%" + wxGoodsListBO.getKeyword() + "%");
        }
        if (wxGoodsListBO.getCategoryId() != null && wxGoodsListBO.getCategoryId() != 0) {
            criteria.andCategoryIdEqualTo(wxGoodsListBO.getCategoryId());
        }
        if (wxGoodsListBO.getBrandId() != null) {
            criteria.andBrandIdEqualTo(wxGoodsListBO.getBrandId());
        }
        if (wxGoodsListBO.getIsNew() != null) {
            criteria.andIsNewEqualTo(wxGoodsListBO.getIsNew());
        }
        if (wxGoodsListBO.getIsHot() != null) {
            criteria.andIsHotEqualTo(wxGoodsListBO.getIsHot());
        }
        //限定排序是升序还是降序
        List<MarketGoods> marketGoodsList = marketGoodsMapper.selectByExample(marketGoodsExample, basePageInfo.getOrder());
        //List<MarketGoods> marketGoodsList = marketGoodsMapper.selectByExample(marketGoodsExample, "desc");
        PageInfo<MarketGoods> pageInfo = new PageInfo<>(marketGoodsList);
        WxGoodsListVO data = WxGoodsListVO.data(pageInfo);

        //获得filterCategoryList
        List<Integer> categoryList = marketGoodsList.stream().map(s -> s.getCategoryId()).distinct().collect(Collectors.toList());
        List<MarketCategory> filterCategoryList = new ArrayList<>();
        MarketCategoryExample marketCategoryExample = new MarketCategoryExample();
        for (Integer id : categoryList) {
            marketCategoryExample.createCriteria().andIdEqualTo(id);
            List<MarketCategory> marketCategoryList = marketCategoryMapper.selectByExample(marketCategoryExample);
            filterCategoryList.add(marketCategoryList.get(0));
            marketCategoryExample.clear();
        }
        data.setFilterCategoryList(filterCategoryList);
        return data;
    }

    @Override
    /**
     * @author 长平居士
     * @description 添加历史记录
     * @date 2022/7/21 18:43
     *
     * @param wxGoodsListBO
     * @return void
     */
    public void addHistory(WxGoodsListBO wxGoodsListBO) {
        // 获取用户 ID
        Subject subject = SecurityUtils.getSubject();
        if (subject.getPrincipals() == null) {
            return;
        }
        MarketUser principal = (MarketUser) subject.getPrincipals().getPrimaryPrincipal();
        MarketUserExample userExample = new MarketUserExample();
        MarketUserExample.Criteria userCriteria = userExample.createCriteria();
        userCriteria.andUsernameEqualTo(principal.getUsername());
        Integer userID = marketUserMapper.selectByExample(userExample).get(0).getId();

        // 获取插入数据
        MarketSearchHistory data = new MarketSearchHistory();
        data.setKeyword(wxGoodsListBO.getKeyword());
        data.setAddTime(new Date());
        data.setUpdateTime(new Date());
        data.setUserId(userID);

        // 判空
        MarketSearchHistoryExample shExample = new MarketSearchHistoryExample();
        MarketSearchHistoryExample.Criteria shCriteria = shExample.createCriteria();
        if (wxGoodsListBO.getKeyword() == null) {
            return;
        }
        shCriteria.andKeywordEqualTo(wxGoodsListBO.getKeyword());
        if (!marketSearchHistoryMapper.selectByExample(shExample).isEmpty()) {
            return;
        }

        marketSearchHistoryMapper.insertSelective(data);

    }


}
